from flask import Flask, session
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask.blueprints import Blueprint
from .config import config_dict

db = SQLAlchemy()
migrate = Migrate()


def create_app(config: str) -> Flask:
    """
    工厂函数
    :param config:
    :return:
    """
    app = Flask(__name__)
    try:
        config_class = config_dict[config]
    except KeyError:
        config_class = config_dict['default']
    app.config.from_object(config_class)

    @app.route('/test')
    def say_hello():
        return "say hello..."

    register_extends(app)
    register_bps(app)
    register_shell_context(app)
    register_template_context(app)
    return app


def register_extends(app: Flask):
    """
    注册扩展
    :return:
    """
    global db
    db.init_app(app)
    migrate.init_app(app, db)


def register_bps(app: Flask):
    """
    注册蓝图
    :return:
    """
    from app.blueprints.admin import admin_bp
    app.register_blueprint(admin_bp)


def register_shell_context(app: Flask):
    @app.shell_context_processor
    def shell_context():
        return {
            'User': User,
            'Role': Role,
        }


def register_template_context(app: Flask):
    @app.context_processor
    def template_context():
        login_user: User = session.get('login_user')
        return {'login_user': login_user}


app = create_app('dev')
from .models import User, Role
